import axios from 'axios';
import store from 'src/store';
// import { ElLoading } from 'element-plus';
import { msgFn } from 'src/utils';
import { removePending, addPending } from 'src/plugins/http/cancelToken';
import { Toast, LoadingType } from 'vant';

declare interface LoadingObj {
    message: string
    forbidClick: boolean
    duration: number
    loadingType: LoadingType
}
const { state } = store;
let loadingInstance: any = null;
const loadConfig: LoadingObj = {
    'message': '玩命加载中...',
    'forbidClick': true,
    'duration': 0,
    'loadingType': 'spinner'
};


// 添加请求拦截器
axios.interceptors.request.use((config: any) => {
    config.headers.secret = state.userInfo.secret;
    config.headers.appkey = 'a33a1726d93a401b812bafff8d5b73c3';
    removePending(config);
    addPending(axios, config);
    return config;
}, error => Promise.reject(error));

// 添加响应拦截器
axios.interceptors.response.use((response: any) => {
    removePending(response);
    return response;
}, error => Promise.resolve(error.response));


const httpServer = (opts: any, data: any) => {
    // 公共参数
    const Public = {};
    // opts.isLoading = opts.isLoading ? opts.isLoading : '1';
    // console.log(opts);
    if (Number(opts.isLoading)) {
        loadConfig.message = opts.text ? opts.text : loadConfig.message;
        Toast.loading(loadConfig);
    }
    opts.method = opts.method ? opts.method.toLowerCase().replace(/(^\s*)|(\s*$)/g, '') : 'post';
    const defaultOpts = {
        'method': 'post',
        'baseURL': '',
        'url': '',
        'timeout': 10000,
        'params': UtilTools.extend(Public, data),
        'data': UtilTools.extend(Public, data),
        'headers': opts.method === 'get' ? {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
            'Content-Type': 'application/json; charset=UTF-8'
        } : {
            'Content-Type': 'application/json; charset=UTF-8'
        }
    };
    const httpDefaultOpts = UtilTools.extend(defaultOpts, opts);
    if (opts.method === 'get') {
        delete httpDefaultOpts.data;
    } else {
        delete httpDefaultOpts.params;
    }
    return new Promise((resolve, reject) => {
        axios(httpDefaultOpts).then(res => {
            if (loadingInstance) { loadingInstance.close(); }
            const { msg = 'internal server error', code = 500 } = res?.data;
            if (code >= 200 && code < 400) {
                resolve(res?.data);
            } else if (code === 401) {
                store.commit('_logout');
                msgFn(msg);
                setTimeout(() => {
                    window.location.href = `${window.location.origin}/#/login`;
                    return false;
                }, 1001);
            } else {
                reject(msg || '请求失败，请稍后再试');
            }
        }).catch(error => {
            if (loadingInstance) { loadingInstance.close(); }
            reject(error.error || '请求失败，请稍后再试');
        });
    });
};

export default httpServer;
